package com.controller;
import com.Tool.HCNetSDK;
import com.domain.DoorAlarmRecord;
import com.domain.DoorCar;
import com.domain.DoorDevice;
import com.domain.DoorRecord;
import com.repository.DeviceRepo;
import com.server.AlarmRecordServer;
import com.server.CarServer;
import com.server.DeviceServer;
import com.server.RecordServer;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/park/interface")
public class SetupAlarmChan {
    @Autowired
    AlarmRecordServer alarmRecordServer;
    @Resource
    public RecordServer recordServer;
    @Resource
    public CarServer carServer;
    @Autowired
    DeviceServer deviceServer;
    NativeLong lAlarmHandle;//报警布防句柄
    HCNetSDK.FMSGCallBack_V31 fMSFCallBack_V31;//报警回调函数实现
    static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE;
    @GetMapping(value = "/111")
    public void zzz() {

/*        if (lAlarmHandle.intValue() < 0)//尚未布防,需要布防
        {*/
        HCNetSDK.MY_USER_DATA userData = new HCNetSDK.MY_USER_DATA();
        userData.dwSize = userData.size();
        userData.byteData = "1234567".getBytes();
        Pointer pUserData = userData.getPointer();
        //注册
        List<DoorDevice> doorDeviceList = deviceServer.findAll();
        List<NativeLong> luserID = new ArrayList<>();
      
        for (DoorDevice doorDevice:doorDeviceList
             ) {
          String  deviceIp =  doorDevice.getIp();
            NativeLong userID= lianjie.lianjie(deviceIp,doorDevice.getPort(),doorDevice.getAccount(),doorDevice.getPassword());
            if (userID.intValue()==-1){
                System.out.println("IP为"+deviceIp+"的主机连接失败================");
            }
            luserID.add(userID);
        }
       // NativeLong userID= lianjie.lianjie("192.168.3.188","8000");
            if (fMSFCallBack_V31 == null) {
                fMSFCallBack_V31 = new FMSGCallBack_V31();
                if (!hCNetSDK.NET_DVR_SetDVRMessageCallBack_V31(fMSFCallBack_V31, pUserData)) {
                    System.out.println("设置回调函数失败!");
                }
            }
            HCNetSDK.NET_DVR_SETUPALARM_PARAM m_strAlarmInfo = new HCNetSDK.NET_DVR_SETUPALARM_PARAM();
            m_strAlarmInfo.dwSize = m_strAlarmInfo.size();
            m_strAlarmInfo.byLevel = 1;
            m_strAlarmInfo.byAlarmInfoType = 1;
            m_strAlarmInfo.write();
        
        for (NativeLong userID:luserID
             ) {
            lAlarmHandle = hCNetSDK.NET_DVR_SetupAlarmChan_V41(userID, m_strAlarmInfo);
            if (lAlarmHandle.intValue() == -1) {
                System.out.println("布防失败");
                // JOptionPane.showMessageDialog(null, "布防失败");
            } else {
                System.out.println("布防成功");
                //  JOptionPane.showMessageDialog(null, "布防成功");
            }
        }

         /*   lAlarmHandle = hCNetSDK.NET_DVR_SetupAlarmChan_V41(lianjie.lianjie("192.168.3.188","8000"), m_strAlarmInfo);
            if (lAlarmHandle.intValue() == -1) {
                System.out.println("布防失败");
            } else {
                System.out.println("布防成功");
            }*/
      //  }
    }
    public class FMSGCallBack_V31 implements HCNetSDK.FMSGCallBack_V31
    {
        public boolean invoke(NativeLong lCommand, HCNetSDK.NET_DVR_ALARMER pAlarmer, Pointer pAlarmInfo, int dwBufLen, Pointer pUser)
        {
            AlarmDataHandle(lCommand, pAlarmer, pAlarmInfo, dwBufLen, pUser);
            return true;
        }


        public void AlarmDataHandle(NativeLong lCommand, HCNetSDK.NET_DVR_ALARMER pAlarmer, Pointer pAlarmInfo, int dwBufLen, Pointer pUser)
        {
            String sAlarmType = new String();
            //DefaultTableModel alarmTableModel = ((DefaultTableModel) jTableAlarm.getModel());//获取表格模型
            String[] newRow = new String[3];
            //报警时间
            Date today = new Date();
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String[] sIP = new String[2];

            sAlarmType = new String("lCommand=") + lCommand.intValue();
            //lCommand是传的报警类型
            switch (lCommand.intValue())
            {
                case HCNetSDK.COMM_ALARM_V30:
                    HCNetSDK.NET_DVR_ALARMINFO_V30 strAlarmInfoV30 = new HCNetSDK.NET_DVR_ALARMINFO_V30();
                    strAlarmInfoV30.write();
                    Pointer pInfoV30 = strAlarmInfoV30.getPointer();
                    pInfoV30.write(0, pAlarmInfo.getByteArray(0, strAlarmInfoV30.size()), 0, strAlarmInfoV30.size());
                    strAlarmInfoV30.read();
                    switch (strAlarmInfoV30.dwAlarmType)
                    {
                        case 0:
                            sAlarmType = sAlarmType + new String("：信号量报警") + "，"+ "报警输入口：" + (strAlarmInfoV30.dwAlarmInputNumber+1);
                            break;
                        case 1:
                            sAlarmType = sAlarmType + new String("：硬盘满");
                            break;
                        case 2:
                            sAlarmType = sAlarmType + new String("：信号丢失");
                            break;
                        case 3:
                            sAlarmType = sAlarmType + new String("：移动侦测") + "，"+ "报警通道：";
                            for (int i=0; i<64; i++)
                            {
                                if (strAlarmInfoV30.byChannel[i] == 1)
                                {
                                    sAlarmType=sAlarmType + "ch"+(i+1)+" ";
                                }
                            }
                            break;
                        case 4:
                            sAlarmType = sAlarmType + new String("：硬盘未格式化");
                            break;
                        case 5:
                            sAlarmType = sAlarmType + new String("：读写硬盘出错");
                            break;
                        case 6:
                            sAlarmType = sAlarmType + new String("：遮挡报警");
                            break;
                        case 7:
                            sAlarmType = sAlarmType + new String("：制式不匹配");
                            break;
                        case 8:
                            sAlarmType = sAlarmType + new String("：非法访问");
                            break;
                    }
                    newRow[0] = dateFormat.format(today);
                    //报警类型
                    newRow[1] = sAlarmType;
                    //报警设备IP地址
                    sIP = new String(pAlarmer.sDeviceIP).split("\0", 2);
                    newRow[2] = sIP[0];
                  //  alarmTableModel.insertRow(0, newRow);
                    break;
                case HCNetSDK.COMM_ALARM_RULE:
                    HCNetSDK.NET_VCA_RULE_ALARM strVcaAlarm = new HCNetSDK.NET_VCA_RULE_ALARM();
                    strVcaAlarm.write();
                    Pointer pVcaInfo = strVcaAlarm.getPointer();
                    pVcaInfo.write(0, pAlarmInfo.getByteArray(0, strVcaAlarm.size()), 0, strVcaAlarm.size());
                    strVcaAlarm.read();


                    newRow[0] = dateFormat.format(today);
                    //报警类型
                    newRow[1] = sAlarmType;
                    //报警设备IP地址
                    sIP = new String(pAlarmer.sDeviceIP).split("\0", 2);
                    newRow[2] = sIP[0];
                  //  alarmTableModel.insertRow(0, newRow);

                    if(strVcaAlarm.dwPicDataLen>0)
                    {
                        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
                        String newName = sf.format(new Date());
                        FileOutputStream fout;
                        try {
                            fout = new FileOutputStream(newName+"_VCA.jpg");
                            //将字节写入文件
                            long offset = 0;
                            ByteBuffer buffers = strVcaAlarm.pImage.getPointer().getByteBuffer(offset, strVcaAlarm.dwPicDataLen);
                            byte [] bytes = new byte[strVcaAlarm.dwPicDataLen];
                            buffers.rewind();
                            buffers.get(bytes);
                            fout.write(bytes);
                            fout.close();
                        }catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    break;

                case HCNetSDK.COMM_ALARM_ACS: //门禁主机报警信息
                    HCNetSDK.NET_DVR_ACS_ALARM_INFO strACSInfo = new HCNetSDK.NET_DVR_ACS_ALARM_INFO();
                    strACSInfo.write();
                    Pointer pACSInfo = strACSInfo.getPointer();
                    pACSInfo.write(0, pAlarmInfo.getByteArray(0, strACSInfo.size()), 0, strACSInfo.size());
                    strACSInfo.read();

                    sAlarmType = sAlarmType + "：门禁主机报警信息，卡号："+  new String(strACSInfo.struAcsEventInfo.byCardNo).trim() + "，卡类型：" +
                            strACSInfo.struAcsEventInfo.byCardType + "，报警主类型：" + strACSInfo.dwMajor + "，报警次类型：" + strACSInfo.dwMinor+ "，详细参数：" +strACSInfo.struAcsEventInfo;

                    System.out.println("" +
                            "" +sAlarmType);

                    if(!new String(strACSInfo.struAcsEventInfo.byCardNo).trim().equals("")) {
                        //进行查询表。添加数据
                        DoorRecord doorRecord =new DoorRecord();
                        doorRecord.setCardno(new String(strACSInfo.struAcsEventInfo.byCardNo).trim());
                        System.out.println("byCardNo="+new String(strACSInfo.struAcsEventInfo.byCardNo).trim());

                        DoorCar car1= carServer.findByDepartment(new String(strACSInfo.struAcsEventInfo.byCardNo).trim());
                        System.out.println("car1="+car1);
                        doorRecord.setName(car1.getName());
                        if(strACSInfo.struAcsEventInfo.dwDoorNo==1){
                            doorRecord.setNote2("门1");
                        }else {
                            doorRecord.setNote2("门2");
                        }
                        if(strACSInfo.struAcsEventInfo.dwCardReaderNo==1||strACSInfo.struAcsEventInfo.dwCardReaderNo==3){
                            doorRecord.setNote3("进门");
                        }else {
                            doorRecord.setNote3("出门");
                        }
                        String dateTime= dateFormat.format(new Date());
                        if(strACSInfo.dwMinor==1){
                            doorRecord.setNote1("卡片开门成功");
                        }else if(strACSInfo.dwMinor==38){
                            doorRecord.setNote1("指纹开门成功");

                        }else if(strACSInfo.dwMinor==39){
                            doorRecord.setNote1("指纹开门失败");

                        }else {
                            doorRecord.setNote1("卡片开门失败");
                        }
                        doorRecord.setTime(dateTime);
                        recordServer.save(doorRecord);
                        if(strACSInfo.dwMinor!=1){
                            Date date = new Date();
                            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                            String newdate = dateFormat1.format(date);
                            Long countNote1 = recordServer.findCountByTime(new String(strACSInfo.struAcsEventInfo.byCardNo).trim() ,"开门失败",newdate);
                            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+countNote1);
                            if (countNote1>=3){
                                DoorAlarmRecord doorAlarmRecord = new DoorAlarmRecord();
                                doorAlarmRecord.setName(car1.getName());
                                doorAlarmRecord.setCardno(doorRecord.getCardno());
                                doorAlarmRecord.setOpenDoorStatus("危险警报");
                                doorAlarmRecord.setDoorNumber(doorRecord.getNote2());
                                doorAlarmRecord.setInOut(doorRecord.getNote3());
                                doorAlarmRecord.setTime(dateTime);
                                doorAlarmRecord.setNote1(countNote1+"");
                                alarmRecordServer.saveAlarmRec(doorAlarmRecord);
                            }
                        }
                    }

                    newRow[0] = dateFormat.format(today);
                    //报警类型
                    newRow[1] = sAlarmType;
                    //报警设备IP地址
                    sIP = new String(pAlarmer.sDeviceIP).split("\0", 2);
                    newRow[2] = sIP[0];
                  //  alarmTableModel.insertRow(0, newRow);

                    if(strACSInfo.dwPicDataLen>0)
                    {
                        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
                        String newName = sf.format(new Date());
                        FileOutputStream fout;
                        try {
                            String filename = newName+"_ACS_card_"+ new String(strACSInfo.struAcsEventInfo.byCardNo).trim()+".jpg";
                            fout = new FileOutputStream(filename);
                            //将字节写入文件
                            long offset = 0;
                            ByteBuffer buffers = strACSInfo.pPicData.getByteBuffer(offset, strACSInfo.dwPicDataLen);
                            byte [] bytes = new byte[strACSInfo.dwPicDataLen];
                            buffers.rewind();
                            buffers.get(bytes);
                            fout.write(bytes);
                            fout.close();
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    break;
            }
        }

    }
}
